/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: EnvironmentMeasurement_Dummy.cpp,v 1.1 2009-06-18 08:55:28 amaula Exp $
 *
 * \file
 * \brief Dummy implementation for testing the EnvironmentMeasurementServer interface.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 ******************************************************************************
 * NOTE: The following 'Module Info' should be kept up-to-date. Do NOT
 * change its format, insert your information according to the template.
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 *
 * Provides Interfaces:
 * - EnvironmentMeasurement
 *
 * Needs Interfaces:
 *
 * General information:
 * 
 ******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "EnvironmentMeasurementServer.hpp"

//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::EnvironmentMeasurement;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup;
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tEnvironmentMeasurementDummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-f conf_file]\t\tUse 'conf_file' as configuration file for this module\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  // Construct an MaCICtrlServer instance
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);

  // Construct instance of EnvironmentMeasurementServer
  CEnvironmentMeasurementServer es(&mcs, 0, "Environment measurement", "EnvironmentMeasurementDummy");

  // Construct instance of DummyData && Init to use internal BinBag
  CEnvironmentMeasurementData ed;
  ed.CreateInternalBinBag();
  //Construct message source
  SMessageSource ms;

  // Create alarm data.
  Alarm::CAlarmData ad;
  ad.CreateInternalBinBag();

  // Set GroupName for MaCICtrlServer and Instance for AlarmServer.
  mcs.SetGroupName(macigroup);
  es.SetInterfaceInstanceName("EnvironmentMeasuementDummyInstance");

  // Init random number generator
  srandom(time(NULL));
  
  // Enable the Reporting interface.
  es.EnableAlarmServer();
  assert(es.GetAlarmServerPtr() != NULL);


   if (es.Open() == KMaCIOK) {
   
     EMaCIError e;

    // At this point, we have a preconnected GIMI, so now its up to you
    // to do things.  For more examples of functionality and structure,
    // see other MaCI modules, such as Alarm_Dummy.cpp.
    while(run) {
      CEnvironmentMeasurement2D em2dData;
      e = es.WaitCommand(ed, ms, 1000);
      if (e == KMaCIOK) {
        const TCommand *c = ed.GetCommand();
        if (c) {
          dPrint(2,"Got command: %d", c->cmd);
          
          // Check whether it was the one which requires an answer.
          if (c->cmd == KCommandGetPositionWithEnvironment) {
            dPrint(1,"Got Command KCommandGetPositionWithEnvironment from %08x.", ms.gimnetID);
            if(ed.GetEnvironmentMeasurement(&em2dData)){
              dPrint(1,"Data contains Environment measurement. Replying..");
              // Yes it was! So send a reply
              
              
              // Construct event data
              CEnvironmentMeasurementData edr;
              edr.CreateInternalBinBag();
              edr.SetCommand(TCommand(KReplyPositionWithEnvironment));
              edr.SetPose2D(TPose2D(11.11,22.22, 3.14));
              edr.SetVariance2D(TVariance2D(0.68,0.32,0.23)); 
              
              // Send as reply. Can be picked from queue as is - so no
              // need for extra identification information.
              es.SendReply(edr, ms);
           
              dPrint(2,"Replying Pose with values (%f,%f,%f) and Variance (%f,%f,%f) as reply with messageID %d",
                     11.11,22.22, 3.14,
                     0.68,0.32,0.23,
                     ms.messageID);
            }else{
              dPrint(1,"Data didn't contain Environment measurement. Ignoring..");
            }
          }
          
          // Print command contents for Demo purposes.
          ed.Print(2);
          
        } else {
          dPrint(1,"Got Command, but no Command element present???");
          
        }
    }
      
    }

    // Add a call to gimi:stop()
    g.stop();

   
  } else {
    dPrint(1,"Failed to open CEnvironmentMeasuremenServer instance! Fatal error.");
    return -1;

  }
  

  return 0;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.1 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'f':
      configurationFile = optarg;
      dPrint(3,"Using configuration file: '%s'", optarg);
      /*if (ParseConfiguration(localConfig, configurationFile) == true) {
        dPrint(4,"Succesfully parsed configuration file '%s'", optarg);
      } else {
        dPrint(1,"Parsing configuration failed! Fatal error. Exit.");
        exit(1);
        }*/
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(3,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
//******************************************************************************



